package com.jingzhi.huimiao.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import android.util.Log;

/**
 * 从网络获取数据的工具类
 * 
 * @author cxk
 * 
 * 
 */
public class HttpUtils {

	private static final int TIMEOUT = 10000;// 10秒

	public HttpUtils() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 传送文本,例如Json,xml等
	 */
	public static String sendTxt(String urlPath, String txt, String encoding)
			throws Exception {

		byte[] sendData = txt.getBytes();
		URL url = new URL(urlPath);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(TIMEOUT);
		// 如果通过post提交数据，必须设置允许对外输出数据
		conn.setDoOutput(true);
		conn.setRequestProperty("Content-Type", "text/xml");
		conn.setRequestProperty("Charset", encoding);
		conn.setRequestProperty("Content-Length",
				String.valueOf(sendData.length));
		OutputStream outStream = conn.getOutputStream();
		outStream.write(sendData);
		outStream.flush();
		outStream.close();
		if (conn.getResponseCode() == 200) {
			// 获得服务器响应的数据
			BufferedReader in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), encoding));
			// 数据
			String retData = null;
			String responseData = "";
			while ((retData = in.readLine()) != null) {
				responseData += retData;
			}
			in.close();
			return responseData;
		}
		return "sendText error!";
	}

	public static String sendPostRequest(String urlPath,  
            Map<String, String> params, String encoding) throws Exception {  
        StringBuilder sb = new StringBuilder();  
        // 如果参数不为空  
        if (params != null && !params.isEmpty()) {  
            for (Map.Entry<String, String> entry : params.entrySet()) {  
                // Post方式提交参数的话，不能省略内容类型与长度  
                sb.append(entry.getKey()).append('=').append(  
                        URLEncoder.encode(entry.getValue(), encoding)).append(  
                        '&');  
            }  
            sb.deleteCharAt(sb.length() - 1);  
            
            
        }  
        // 得到实体的二进制数据  
        byte[] entitydata = sb.toString().getBytes();  
        URL url = new URL(urlPath);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(TIMEOUT);  
        // 如果通过post提交数据，必须设置允许对外输出数据  
        conn.setDoOutput(true);  
        // 这里只设置内容类型与内容长度的头字段  
        conn.setRequestProperty("Content-Type",  
                "application/x-www-form-urlencoded");  
        // conn.setRequestProperty("Content-Type", "text/xml");  
        conn.setRequestProperty("Charset", encoding);  
        conn.setRequestProperty("Content-Length", String  
                .valueOf(entitydata.length));  
        OutputStream outStream = conn.getOutputStream();  
        // 把实体数据写入是输出流  
        outStream.write(entitydata);  
        // 内存中的数据刷入  
        outStream.flush();  
        outStream.close();  
       
        
        // 如果请求响应码是200，则表示成功  
        if (conn.getResponseCode() == 200) {  
            // 获得服务器响应的数据  
            BufferedReader in = new BufferedReader(new InputStreamReader(conn  
                    .getInputStream(), encoding));  
            // 数据  
            String retData = null;  
            String responseData = "";  
            while ((retData = in.readLine()) != null) {  
                responseData += retData;  
            }  
            in.close();
            
            return responseData;
        }  
        
        return "sendText error!";  
    }  
	
	//Map<String,Object>
	public static String sendPostObj(String urlPath,  
            Map<String, Object> params, String encoding) throws Exception {  
        StringBuilder sb = new StringBuilder();  
        // 如果参数不为空  
        
//        Log.e("TAG---1111---", params.toString());
        
        if (params != null && !params.isEmpty()) {  
            for (Entry<String, Object> entry : params.entrySet()) {  
                // Post方式提交参数的话，不能省略内容类型与长度  
                sb.append(entry.getKey()).append('=').append(  
                       entry.getValue()).append(  
                        '&');  
            }  
            

//            Log.e("TAG---1---", sb.toString());
            
            sb.deleteCharAt(sb.length() - 1);  
        }  
        // 得到实体的二进制数据  
        byte[] entitydata = sb.toString().getBytes();  
        URL url = new URL(urlPath);  
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(TIMEOUT);  
        // 如果通过post提交数据，必须设置允许对外输出数据  
        conn.setDoOutput(true);  
        // 这里只设置内容类型与内容长度的头字段  
        conn.setRequestProperty("Content-Type",  
                "application/x-www-form-urlencoded");  
        // conn.setRequestProperty("Content-Type", "text/xml");  
        conn.setRequestProperty("Charset", encoding);  
        conn.setRequestProperty("Content-Length", String  
                .valueOf(entitydata.length));  
        OutputStream outStream = conn.getOutputStream();  
        // 把实体数据写入是输出流  
        outStream.write(entitydata);  
        // 内存中的数据刷入  
        outStream.flush();  
        outStream.close();  
        
        
        Log.e("TAG---2---", conn.getResponseCode()+"");
        
        // 如果请求响应码是200，则表示成功  
        if (conn.getResponseCode() == 200) {  
            // 获得服务器响应的数据  
            BufferedReader in = new BufferedReader(new InputStreamReader(conn  
                    .getInputStream(), encoding));  
            // 数据  
            String retData = null;  
            String responseData = "";  
            while ((retData = in.readLine()) != null) {  
                responseData += retData;  
            }  
            in.close();  
            
//            Log.e("TAG---3---", responseData+"");
            
            return responseData;  
        }  
        return "sendText error!";  
    }
	
	
	public static String getJsonContent(String url_path) {

		try {
			URL url = new URL(url_path);
			Log.e("URL-----", url.toString());
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(3000);
			connection.setRequestMethod("GET");
			connection.setDoInput(true);
			// 每次执行到下面判断语句的时候就会抛出异常，是怎么回事？
			if (connection.getResponseCode() == 200) { // 如果数据存在，执行下一步
				return changeInputStream(connection.getInputStream()); // 将输入流转换为二进制数据
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return "";
	}

	private static String changeInputStream(InputStream inputStream) {
		// TODO Auto-generated method stub
		String jsonString = "";
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			jsonString = new String(outputStream.toByteArray());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.e("TAG----------", jsonString);
		return jsonString;
	}
}